package com.epro.dx.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ListView;

import com.epro.dx.BR;
import com.epro.dx.R;
import com.epro.dx.activity.order.ShippingTrackingActivity;
import com.epro.dx.adapter.CommonLVAdapter;
import com.epro.dx.databinding.ActivityOrderTrackBinding;
import com.epro.dx.databinding.ItemOrderTrackListBinding;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.task.DeleteNoticesAsyncTask;
import com.epro.dx.task.GetNoticesAsyncTask;
import com.epro.dx.task.SetNoticeReadAsyncTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.TimeFormat;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.MessageServiceProvider;
import com.weipu.common.facade.model.MessageModel;
import com.weipu.common.util.AlertToast;

import java.util.ArrayList;
import java.util.List;

/**
 * 物流消息列表页
 *
 * @author Zenglw
 * @version [1.0, 2017-6-21]
 */
public class OrderTrackActivity extends BaseFragmentActivity implements CommonLVAdapter.OnLongItemClickListener, CommonLVAdapter.OnItemClickListener {

    private ActivityOrderTrackBinding binding;
    private PullToRefreshListView messagesList;
    private List<MessageModel> mDatas;
    private Handler handler;
    private CommonLVAdapter<MessageModel> mAdapter;
    private int pageIndex = 1;
    private boolean isRefresh;
    private boolean isLoadMore;
    private AlertDialog deleteMessageDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendScreen();
        //当设备的sdk版本大于23，则修改状态栏的颜色为深色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_order_track);
        //设置左边的返回按钮显示
        setLeftBtnContent(true, -1);
        //设置布局
        setTitleContent(R.string.messages_order_title);
        initProperty();
        initView();
        initEvent();
        initData();
    }

    /**
     * 初始化一些属性
     */
    private void initProperty() {
        mDatas = new ArrayList<>();
        handler = new HomeActivity.GlobalHandler(this);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        messagesList = binding.messagesList;
        initAdapter();
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {

        mAdapter = new CommonLVAdapter<MessageModel>(mDatas, BR.info, R.layout.item_order_track_list) {
            @Override
            protected void reFillData(ViewDataBinding binding, int position, MessageModel item) {
                ItemOrderTrackListBinding itemBinding = (ItemOrderTrackListBinding) binding;
                String title = item.getTitle();
                //由于后台返回的内容信息和需求不一致，所以自己拆分字符串进行组装
                itemBinding.trackListContent.setText(getContent(title));

                //设置时间
                itemBinding.trackListTime.setText(TimeFormat.formatTimeToLocal(OrderTrackActivity.this, item.getCreateAt()));

                //根据未读状态来确定未读消息小红点是否显示
                boolean isRead = item.isRead();
                if (isRead) {

                    itemBinding.trackListHasnewPoint.setVisibility(View.GONE);
                } else {
                    itemBinding.trackListHasnewPoint.setVisibility(View.VISIBLE);

                }

                //设置viewmore 箭头的大小
                Drawable drawable1 = getResources().getDrawable(R.drawable.arrow_right);
                drawable1.setBounds(0, 0, 15, 25);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
                itemBinding.trackListViewMore.setCompoundDrawables(null, null, drawable1, null);//只放右边

            }
        };
        messagesList.setAdapter(mAdapter);
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        messagesList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                isRefresh = true;
                isLoadMore = false;
                loadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex++;
                isRefresh = false;
                isLoadMore = true;
                loadData();
            }
        });

        mAdapter.setOnLongItemClickListener(this);
        mAdapter.setOnItemClickListener(this);
//        messagesList.setOnItemClickListener(this);
    }


    @Override
    public void onItemClick(Object model, final int position) {
        //如果消息还没有被读，则请求接口，设置该消息已读
        boolean isRead = mDatas.get(position).isRead();
        if (!isRead) {
            List<String> noticeIds = new ArrayList<>();
            noticeIds.add(mDatas.get(position).getNoticeID());
            //设置已读的网络请求
            AsyncTaskUtil.executeTask(new SetNoticeReadAsyncTask(this,4,
                     (ArrayList<String>) noticeIds, new MyAsyncTaskListenner() {
                @Override
                public void onPreTask() {

                }

                @Override
                public void onPostTask(String result, Object obj) {
                    if ("0".equals(result)) {
                        if (((boolean) obj)) {
                            //设置消息已读成功
                            mDatas.get(position).setRead(true);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }));
        }

        Intent intent = new Intent(this, ShippingTrackingActivity.class);
        intent.putExtra("OrderNumber", mDatas.get(position).getOrderNumber())
                .putExtra("CurrencyCode", "")
                .putExtra("fromOrderTrackPage", true);
        startActivity(intent);
    }

    /**
     * 当列表数据长按时的回调方法
     *
     * @param model    对应item的数据
     * @param position 位置
     */
    @Override
    public void onLongItemClick(Object model, int position) {
        //长按消息列表删除对应消息
        MessageModel messageModel = (MessageModel) model;
        showDeleteMessageDialog(messageModel, position);
    }

    /**
     * 长按删除显示的对话框
     *
     * @param messageModel 要删除的数据
     * @param position     要删除的数据的格式
     */
    private void showDeleteMessageDialog(final MessageModel messageModel, final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OrderTrackActivity.this);
        builder.setTitle(R.string.delete)
                .setMessage(R.string.user_wish_confirm_del);
        builder.setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //取消
                deleteMessageDialog.dismiss();
            }
        });
        builder.setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteMessageDialog.dismiss();
                //确认删除
                if (null != messageModel) {
                    ArrayList<String> notices = new ArrayList<String>();
                    notices.add(messageModel.getNoticeID());
                    AsyncTaskUtil.executeTask(new DeleteNoticesAsyncTask(OrderTrackActivity.this, MessageServiceProvider.ACTIONTYPE_NOTICEIDS, notices, new MyAsyncTaskListenner() {

                        @Override
                        public void onPreTask() {
                            showWaitingDialog();
                        }

                        @Override
                        public void onPostTask(String result, Object obj) {
                            if (!isFinishing()) {
                                hideWaitingDialog();
                                if ("0".equals(result)) {
                                    //删除成功，将内存数据删除
                                    mDatas.remove(position);
                                    mAdapter.notifyDataSetChanged();
                                } else {
                                    AlertToast.alert(OrderTrackActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                                }
                            }
                        }
                    }));
                }
            }
        });
        deleteMessageDialog = builder.create();
        deleteMessageDialog.show();
    }


    /**
     * 根据后台返回的数据获取分段获取内容
     *
     * @param title 后台返回的内容
     * @return 拆分拼接好的内容
     */
    private String getContent(String title) {
        String[] contentSplit = title.split("\\r\\n");
        int length = contentSplit.length;
        StringBuffer buffer = new StringBuffer();
        if (length == 4) {
            buffer.append(contentSplit[1])
                    .append("\r\n")
                    .append(contentSplit[2])
                    .append("\r\n")
                    .append(contentSplit[3]);
        } else if (contentSplit.length == 3) {
            buffer.append(contentSplit[1])
                    .append("\r\n")
                    .append(contentSplit[2]);
        }
        return buffer.toString();
    }

    /**
     * 加载列表数据
     */
    private void loadData() {
        AsyncTaskUtil.executeTask(new GetNoticesAsyncTask(this, MessageModel.NOTICETYPE_ORDER, pageIndex, Constant.LIST_PAGE_COUNT, new MyAsyncTaskListenner() {

            @Override
            public void onPreTask() {
                showLoadingLayout(null);
            }

            @Override
            public void onPostTask(String result, Object obj) {
                messagesList.onRefreshComplete();
                if (!isFinishing()) {
                    hideAllLayout();
                    if ("0".equals(result)) {
                        if (isRefresh && obj != null) {
                            mDatas.clear();

                            mDatas.addAll(((ArrayList<MessageModel>) obj));

                        } else if (isLoadMore) {
                            if (obj != null) {
                                mDatas.addAll(((ArrayList<MessageModel>) obj));
                            }
                        }
                        mAdapter.notifyDataSetChanged();

                    } else {
                        AlertToast.alert(OrderTrackActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                    }
                }
            }
        }));
    }

    /**
     * 初始化数据,从上个页面获取
     */
    private void initData() {
        Bundle bundleExtra = getIntent().getBundleExtra(ServerConstant.MessageCenter.INTENT_BUNDLE);
        ArrayList<MessageModel> messageList = bundleExtra.getParcelableArrayList("MessageList");
        mDatas.addAll(messageList);
        if (mDatas.size() == 0) {
            messagesList.setMode(PullToRefreshBase.Mode.DISABLED);//没有数据，设置上拉加载和下拉刷新不可用
        } else {
            messagesList.setMode(PullToRefreshBase.Mode.BOTH);//有数据，设置上拉加载和下拉刷新可用
        }
        mAdapter.notifyDataSetChanged();

    }

    /**
     * 设置状态栏的颜色
     */
    @Override
    protected void setStateColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityUtil.setStatusColor(this, getResources().getColor(R.color.white), null);
        } else {
            ActivityUtil.setStatusColor(this, 0, null);
        }
    }
}
